import { moveFrequency, roleSpeed as speed } from "../config.js";
import { fire } from "../fire.js";
import { boxH, boxW, role } from "../index.js";
const setTransfrom = (po) => {
    return `translate(${po.x}px, ${po.y}px)`;
};
export const getPosition = (ele) => {
    const po = ele.style.transform;
    const xy = po.slice(po.indexOf("(") + 1, po.indexOf(")")).split(",");
    return {
        x: +xy[0].replace("px", ""),
        y: +xy[1].replace("px", ""),
    };
};
export const getRolePosition = () => {
    return getPosition(role);
};
//指令动作
const actions = () => {
    const keys = Object.keys(scheduler);
    keys.forEach((k) => {
        //判断移动的位置是否是边界
        switch (k) {
            case "a":
                move("a");
                break;
            case "d":
                move("d");
                break;
            case "w":
                move("w");
                break;
            case "s":
                move("s");
                break;
            case "j":
                fire(k);
                break;
        }
    });
    // requestAnimationFrame(actions);
};
setInterval(actions, 100);
// requestAnimationFrame(actions);
//移动指令
let timer;
const move = (key) => {
    if (typeof timer === "number")
        return;
    console.log(timer);
    setTimeout(() => {
        timer = undefined;
    }, 1000 / moveFrequency);
    const rolePosition = getRolePosition();
    switch (key) {
        case "a":
            if (rolePosition.x <= 0)
                return;
            rolePosition.x -= speed;
            role.style.transform = setTransfrom(rolePosition);
            break;
        case "d":
            if (rolePosition.x >= boxW) {
                rolePosition.x = boxW;
            }
            else {
                rolePosition.x += speed;
            }
            role.style.transform = setTransfrom(rolePosition);
            break;
        case "w":
            if (rolePosition.y <= 0)
                return;
            rolePosition.y -= speed;
            role.style.transform = setTransfrom(rolePosition);
            break;
        case "s":
            if (rolePosition.y + 10 >= boxH) {
                rolePosition.y = boxH;
            }
            else {
                rolePosition.y += speed;
            }
            role.style.transform = setTransfrom(rolePosition);
            break;
    }
};
//指令调度
const scheduler = {};
//设置开始指令
export const setKey = (key) => {
    scheduler[key] || (scheduler[key] = true);
};
//设置结束指令
export const removeKey = (key) => {
    scheduler[key] && delete scheduler[key];
};
//按键触发移动
let keyword = ["a", "s", "d", "w", "j"];
export function transfrom(e) {
    if (!keyword.includes(e.key))
        return;
    setKey(e.key);
}
//停止移动
export function stopTransform(e) {
    if (!keyword.includes(e.key))
        return;
    removeKey(e.key);
}
